package fr.kraml;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

public class RoomFragment extends Fragment {

	ScrollView sv;
	// TextView tv;
	EditText et;
	Button bt;
	View mView;
	RoomFragmentListener mCallback;

	MyListView lv;
	RoomMessageArrayAdapter adapter;
	ArrayList<RoomMessage> messages = new ArrayList<RoomMessage>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		try {
			mCallback = (RoomFragmentListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement LoginFragmentListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment

		mView = inflater.inflate(R.layout.room_fragment, container, false);

		lv = (MyListView) mView.findViewById(R.id.roomListView);
		adapter = new RoomMessageArrayAdapter(this.getActivity(), messages);
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {

				int old_pos_from_end = et.getText().length()
						- et.getSelectionStart();
				String from = messages.get(position).from;
				String mess = et.getText().toString();
				et.setText(from + " > " + mess);
				et.setSelection(et.getText().length() - old_pos_from_end);

			}

		});

		/*
		 * mView = inflater.inflate(R.layout.room_fragment, container, false);
		 * 
		 * sv = (ScrollView) mView.findViewById(R.id.roomScrollView); tv =
		 * (TextView) mView.findViewById(R.id.roomTextView);
		 */
		et = (EditText) mView.findViewById(R.id.roomEditText);
		bt = (Button) mView.findViewById(R.id.roomSendButton);

		bt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCallback.onGroupChatSend(et.getText().toString());
				et.setText("");
			}
		});

		/*
		 * et.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub scrollMyListViewToBottom(); } });
		 */

		MyOnResizeListener orlResized = new MyOnResizeListener() {
			@Override
			public void OnResize(int id, int xNew, int yNew, int xOld, int yOld) {
				scrollMyListViewToBottom();
			}
		};

		lv.SetOnResizeListener(orlResized);

		mCallback.loadBDDMessages();

		/*
		 * et.setImeActionLabel("Envoyer", KeyEvent.KEYCODE_ENTER);
		 * 
		 * et.setOnKeyListener(new OnKeyListener() {
		 * 
		 * @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
		 * // TODO Auto-generated method stub if ((event.getAction() ==
		 * KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { //
		 * Perform action on key press
		 * mCallback.onGroupChatSend(et.getText().toString()); return true; }
		 * return false; } });
		 */

		return mView;

	}

	class RoomMessageArrayAdapter extends ArrayAdapter<RoomMessage> {
		private final Context context;
		private final ArrayList<RoomMessage> messages;

		public RoomMessageArrayAdapter(Context context,
				ArrayList<RoomMessage> messages) {
			super(context, R.layout.room_fragment_item, messages);
			this.context = context;
			this.messages = messages;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View rowView = inflater.inflate(R.layout.room_fragment_item,
					parent, false);
			TextView from = (TextView) rowView
					.findViewById(R.id.room_item_from);
			TextView mess = (TextView) rowView
					.findViewById(R.id.room_item_text);
			// ImageView imageView = (ImageView) rowView
			// .findViewById(R.id.room_item_image);
			if (messages.get(position).from != null) {
				ASV asv = mCallback.getASV(messages.get(position).from);
				int color = Color.parseColor("#AB9F63");
				if (asv.sex.equals("M"))
					color = Color.parseColor("#0000FF");
				if (asv.sex.equals("F"))
					color = Color.parseColor("#FF00FF");
				from.setText(messages.get(position).from + " > ");
				from.setTextColor(color);
				mess.setText(messages.get(position).mess);
				mess.setTextColor(Color.parseColor(messages.get(position).color));
			} else {
				from.setText("");
				mess.setText(messages.get(position).mess);
				mess.setTextColor(Color.parseColor(messages.get(position).color));
			}
			// imageView.setImageDrawable(participants.get(position).avatarBMP);

			return rowView;
		}
	}

	public RoomFragment() {
		// TODO Auto-generated constructor stub
	}

	// Container Activity must implement this interface
	public interface RoomFragmentListener {
		public void onGroupChatSend(String text);

		public void loadBDDMessages();

		public ASV getASV(String username);
	}

	public void displayMessage(String from, String text, String color) {
		// TODO Auto-generated method stub
		/*
		 * tv.append(from + " > " + text + "\n");
		 * 
		 * sv.post(new Runnable() {
		 * 
		 * @Override public void run() { sv.fullScroll(ScrollView.FOCUS_DOWN); }
		 * });
		 */

		messages.add(new RoomMessage(this, from, text, color));
		adapter.notifyDataSetChanged();
		scrollMyListViewToBottom();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		adapter = new RoomMessageArrayAdapter(this.getActivity(), messages);
		lv.setAdapter(adapter);
	}

	private void scrollMyListViewToBottom() {
		lv.post(new Runnable() {
			@Override
			public void run() {
				// Select the last row so it will scroll into view...
				lv.setSelection(adapter.getCount() - 1);
			}
		});
	}

	public void displayPresence(String mess_from, String show) {
		if (show.equals("chat"))
			messages.add(new RoomMessage(this, null, mess_from
					+ " a rejoint le salon", "#468847"));
		else if (show.equals("chat"))
			messages.add(new RoomMessage(this, null, mess_from
					+ " a quitté le salon", "#B94A48"));
		adapter.notifyDataSetChanged();
		scrollMyListViewToBottom();
	}

}
